import React, { Component, useEffect, useState } from 'react';
import { Switch, withRouter, Redirect } from 'react-router-dom';
import { RouterConfig } from './routerConfig';
import Header from './components/Header/Header';
import './App.scss';
import getRouterCore from './routeCreate';
import { Spin } from 'antd';
import registerReducer from './util/registerReducer';
import { RouteComponentPropsPlus } from './util/routerBase';

const Loading = () => {
	return (
		<div className="w100 h100 d-f ac jc">
			<Spin />
		</div>
	);
};

class App extends Component<any, any> {
	state = {
		currentRoute: undefined,
	};
	routerCreate;
	routerRender;
	unsubscribeFromHistory: any;

	constructor(props: any) {
		super(props);
		this.routerCreate = getRouterCore();
		this.routerCreate.config = RouterConfig;
		this.routerCreate.BeforeEnter = (to: any) => {
			return new Promise<void>((resolve) => {
				console.log(to);
				this.setState({
					currentRoute: to,
				});
				props.store.dispatch({
					type: 'UPDATE_ROUTER_INFO',
					data: to,
				});
				resolve();
				// if (Object.keys(props.store.getState().userInfo).length) {
				// 	resolve();
				// } else {
				// 	getUserInfo().then((res) => {
				// 		const { email, name, username, user_id } = res;
				// 		props.store.dispatch({
				// 			type: 'UPDATE_USER_INFO',
				// 			data: { email, name, username, user_id },
				// 		});
				// 		resolve();
				// 	});
				// }
			});
		};
		const Loading = () => {
			return (
				<div className="w100 h100 d-f ac jc">
					<Spin />
				</div>
			);
		};
		this.routerCreate.loading = Loading;
		this.routerRender = this.routerCreate.render();
	}

	render() {
		return (
			<div>
				<Header currentRoute={this.state.currentRoute} />
				<div className="app-content fadeIn" id="appScrollContainer">
					{/* <BreadcrumbPlus routes={RouterConfig} currentRoute={this.state.currentRoute} /> */}
					<Switch>
						{this.routerRender}
						<Redirect to="/404" />
					</Switch>
				</div>
			</div>
		);
	}
}

const userInfo = (state = {}, action: any) => {
	switch (action.type) {
		case 'UPDATE_USER_INFO':
			return { ...state, ...action.data };
		default:
			return state;
	}
};

const routerInfo = (state = {}, action: any) => {
	switch (action.type) {
		case 'UPDATE_ROUTER_INFO':
			return { ...state, ...action.data };
		default:
			return state;
	}
};

registerReducer.register(userInfo, 'userInfo');
registerReducer.register(routerInfo, 'routerInfo');

export default withRouter(App);
